package com.hxh.generater.vue;

import com.hxh.config.Constants;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

public class ProcessFreemarkerTemplate {

    /**
     * @param tempPath: vue / template 下的相对路径
     * @param fileName: 模板名称 ，默认加上.ftl后缀
     * @param data:     替换的数据
     * @return java.lang.String
     * @author HXH
     * @description: 根据模板 和 数据 ，利用freemarker生产代码文件
     * @date 2024/3/13
     **/
    public static String processTemplateIntoString(String tempPath, String fileName, Map<String, ?> data, boolean replaceTwices) throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        String classpath = Constants.vueTemplatePath + tempPath + File.separator;
        //设置模板路径
        configuration.setDirectoryForTemplateLoading(new File(classpath));
        //设置字符集
        configuration.setDefaultEncoding("UTF-8");
        Template template = configuration.getTemplate(fileName + ".ftl");

        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);

        if (!replaceTwices) {
            return content;
        }
        //为什么替换两遍？
        //因为第一次替换的value，可能含有替换的key
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("", content);
        freemarker.template.Template template2 = new freemarker.template.Template("", new StringReader(content));
        StringWriter stringWriter = new StringWriter();
        template2.process(data, stringWriter);
        configuration.setTemplateLoader(stringLoader);
        content = stringWriter.toString();

        return content;
    }

    public static String processTemplateIntoString(String tempPath, String fileName, Map<String, ?> data) throws IOException, TemplateException {
        return processTemplateIntoString(tempPath, fileName, data, true);
    }

    public static String processElementUITemplate(String fileName, Map<String, ?> data) throws IOException, TemplateException {
        return processTemplateIntoString("template\\elementUI", fileName, data, false);
    }


}
